package com.drinks.yiniang.ui.activity.user.order;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;

import com.drinks.yiniang.R;
import com.drinks.yiniang.adapter.listview.RefundGoodsListAdapter;
import com.drinks.yiniang.adapter.listview.UploadImageGridAdapter;
import com.drinks.yiniang.entity.common.UploadImageJson;
import com.drinks.yiniang.entity.goods.RefundGoodsJson;
import com.drinks.yiniang.io.api.CommonApiIO;
import com.drinks.yiniang.io.api.OrderApiIO;
import com.drinks.yiniang.io.http.ProgressRequestBody;
import com.drinks.yiniang.ui.widget.dialog.ContactServiceDialog;
import com.drinks.yiniang.ui.widget.dialog.RefundReasonDialog;
import com.drinks.yiniang.utils.ToastUtils;
import com.hansen.library.Constants;
import com.hansen.library.entity.BaseJson;
import com.hansen.library.io.tuple.Tuple2;
import com.hansen.library.listener.APIRequestCallback;
import com.hansen.library.listener.OnListItemClickListener;
import com.hansen.library.listener.OnNavgationBarClickListener;
import com.hansen.library.pickerimage.PickImageHelper;
import com.hansen.library.pickerimage.activity.PicturePreviewActivity;
import com.hansen.library.pickerimage.model.PhotoInfo;
import com.hansen.library.ui.activity.BaseTranBarActivity;
import com.hansen.library.ui.widget.layout.TextEditLayout;
import com.hansen.library.ui.widget.layout.TextTextArrowLayout;
import com.hansen.library.ui.widget.listview.NoScrollGridView;
import com.hansen.library.ui.widget.listview.NoScrollListView;
import com.hansen.library.ui.widget.nav.NavigationBarLayout;
import com.hansen.library.utils.CommonUtils;
import com.hansen.library.utils.StringUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import static com.hansen.library.pickerimage.constant.Extras.EXTRA_FILE_PATH;
import static com.hansen.library.pickerimage.constant.Extras.EXTRA_FROM_LOCAL;
import static com.hansen.library.pickerimage.constant.Extras.EXTRA_PHOTO_LISTS;

/**
 * 订单退款
 *
 * @author han
 * @date 2019/09/06
 */
public class RefundSubmitActivity extends BaseTranBarActivity implements OnNavgationBarClickListener,
        AdapterView.OnItemClickListener, OnListItemClickListener, RefundReasonDialog.OnRefundReasonChooseListener {

    private final int REQ_UPLOAD = 0x01;

    private final int UPLOAD_MAX_NUM = 9;//上传图片的最大数量

    //nav
    private NavigationBarLayout nav_bar_refund_submit;
    //商品列表
    private NoScrollListView lv_refund_goods;
    //退款原因
    private TextTextArrowLayout ll_refund_reason;
    //退款金额
    private TextEditLayout ll_refund_money;
    //上传凭证
    private NoScrollGridView gv_refund_pic;
    //提交
    private Button btn_refund_submit;

    private PickImageHelper.PickImageOption pickImgOption;

    private RefundGoodsListAdapter mRefundGoodsListAdapter;
    private UploadImageGridAdapter mUploadImageGridAdapter;

    private List<RefundGoodsJson.RefundGoodsList> mGoodsList;
    private List<UploadImageJson.UploadImageData> mImageList;
    private List<RefundGoodsJson.RefundGoodsReason> mReasonList;
    private List<PhotoInfo> mUnLoadImageList;

    private File mFile;

    //订单编号
    private String mOrderNo;
    //商品id (存在表示是单个商品退款)
    private String mGoodsId;
    //退款原因id
    private String mRefundReasonId;

    @Override
    protected void initView() {
        nav_bar_refund_submit = findViewById(R.id.nav_bar_refund_submit);

        lv_refund_goods = findViewById(R.id.lv_refund_goods);

        ll_refund_reason = findViewById(R.id.ll_refund_reason);
        ll_refund_money = findViewById(R.id.ll_refund_money);

        gv_refund_pic = findViewById(R.id.gv_refund_pic);

        btn_refund_submit = findViewById(R.id.btn_refund_submit);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        mContext = this;

        if (getIntent() != null) {
            mOrderNo = getIntent().getStringExtra(Constants.KeyOrderNo);
            mGoodsId = getIntent().getStringExtra(Constants.KeyGoodsId);
        }

        mGoodsList = new ArrayList<>();
        mImageList = new ArrayList<>();
        mReasonList = new ArrayList<>();

        mRefundGoodsListAdapter = new RefundGoodsListAdapter(mContext, mGoodsList);
        mUploadImageGridAdapter = new UploadImageGridAdapter(mContext, mImageList);

        lv_refund_goods.setAdapter(mRefundGoodsListAdapter);
        gv_refund_pic.setAdapter(mUploadImageGridAdapter);

        getRefundGoodsList();
    }

    @Override
    protected void initListener() {
        nav_bar_refund_submit.setOnNavgationBarClickListener(this);
        ll_refund_reason.setOnClickListener(this);
        ll_refund_money.setOnClickListener(this);
        btn_refund_submit.setOnClickListener(this);

        gv_refund_pic.setOnItemClickListener(this);
        mUploadImageGridAdapter.setOnListItemClickListener(this);
    }

    @Override
    public void widgetClick(View v) {
        switch (v.getId()) {
            case R.id.ll_refund_reason://退款原因
                RefundReasonDialog dialog = RefundReasonDialog.newInstance(mReasonList);

                dialog.show(getSupportFragmentManager(), Constants.TAG_REASON_LIST_DIALOG);
                break;
            case R.id.btn_refund_submit://提交
                submitRefund();
                break;
            default:
                break;
        }
    }

    @Override
    public int getTranBarResID() {
        return R.layout.activity_refund_submit;
    }

    @Override
    public void onBackClick(View v) {
        finish();
    }

    @Override
    public void onEditClick(View v) {
        ContactServiceDialog dialog = ContactServiceDialog.newInstance();

        dialog.show(getSupportFragmentManager(), Constants.TAG_CONTACT_SERVICE_DIALOG);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        switch (view.getId()) {
            case R.id.fl_grid_add_pic://选择图片
                initPickerImage();
                break;
            default://预览
                previewPic(position);
                break;
        }
    }

    @Override
    public void onItemClick(View mView, int position) {
        switch (mView.getId()) {
            case R.id.iv_grid_upload_delete://删除
                if (CommonUtils.isArrayIndexOutOfBounds(mImageList, position)) {
                    return;
                }

                mImageList.remove(position);

                mUploadImageGridAdapter.notifyDataSetChanged();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQ_UPLOAD://图片上传
                    doUploadFile(data);
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void onReasonChooseClick(String code, String value) {
        mRefundReasonId = code;

        ll_refund_reason.setArrowText(value);
    }

    private void initPickerImage() {
        if (pickImgOption == null) {
            pickImgOption = new PickImageHelper.PickImageOption();
            pickImgOption.multiSelect = true;
        }

        pickImgOption.multiSelectMaxCount = UPLOAD_MAX_NUM > CommonUtils.getListSize(mImageList) ? UPLOAD_MAX_NUM - CommonUtils.getListSize(mImageList) : 0;

        PickImageHelper.pickImage(mContext, REQ_UPLOAD, pickImgOption);
    }

    //预览图片
    private void previewPic(int position) {
        if (CommonUtils.isArrayIndexOutOfBounds(mImageList, position)) {
            return;
        }

        List<String> urlList = new ArrayList<>();

        for (int i = 0; i < mImageList.size(); i++) {
            urlList.add(mImageList.get(i).getOriginal());
        }

        Intent mIntent = new Intent(mContext, PicturePreviewActivity.class);
        mIntent.putExtra(Constants.KeyPos, position);

        mIntent.putStringArrayListExtra(Constants.KeyUrl, (ArrayList<String>) urlList);

        startActivity(mIntent);
    }

    //提交退款
    private void submitRefund() {
        if (StringUtils.isEmpty(mOrderNo)) {
            ToastUtils.showShort(getString(R.string.text_the_order_not_exist));
            return;
        }

        if (StringUtils.isEmpty(mRefundReasonId)) {
            ToastUtils.showShort(getString(R.string.text_select_refund_reason));
            return;
        }

        String refundMoney = ll_refund_money.getEditText();

        if (StringUtils.isEmpty(refundMoney)) {
            ToastUtils.showShort(getString(R.string.text_hint_input_refund_money));
            return;
        }

        showLoadingDialog();

        StringBuilder stringGoods = new StringBuilder();

        for (int i = 0; i < mGoodsList.size(); i++) {
            if (i == (mGoodsList.size() - 1)) {
                stringGoods.append(mGoodsList.get(i).getGoods_id());
            } else {
                stringGoods.append(mGoodsList.get(i).getGoods_id());
                stringGoods.append(",");
            }
        }

        StringBuilder stringImg = new StringBuilder();

        for (int i = 0; i < mImageList.size(); i++) {
            if (!StringUtils.isEmpty(mImageList.get(i).getId())) {
                if (i == (mImageList.size() - 1)) {
                    stringImg.append(mImageList.get(i).getId());
                } else {
                    stringImg.append(mImageList.get(i).getId());
                    stringImg.append(",");
                }
            }
        }

        OrderApiIO.getInstance().submitRefundGoods(mOrderNo, stringGoods.toString(), mRefundReasonId, refundMoney,
                stringImg.toString(), new APIRequestCallback<BaseJson, Tuple2<Integer, String>>() {
                    @Override
                    public void onSuccess(BaseJson res) {
                        ToastUtils.showShort(R.string.text_submit_success);
                        finish();
                    }

                    @Override
                    public void onError(Tuple2<Integer, String> error) {
                        ToastUtils.showShort(error._2);
                    }

                    @Override
                    public void onComplete() {
                        dismissDialog();
                    }
                });
    }

    private void doUploadFile(Intent data) {
        if (!data.getBooleanExtra(EXTRA_FROM_LOCAL, false)) {
            String path = data.getStringExtra(EXTRA_FILE_PATH);

            if (StringUtils.isEmpty(path)) {
                return;
            }

            if (mUnLoadImageList == null) {
                mUnLoadImageList = new ArrayList<>();
            }

            mUnLoadImageList.clear();

            PhotoInfo photoInfo = new PhotoInfo();
            photoInfo.setAbsolutePath(path);
            mUnLoadImageList.add(photoInfo);
        } else {
            mUnLoadImageList = (List<PhotoInfo>) data.getSerializableExtra(EXTRA_PHOTO_LISTS);
        }

        if (CommonUtils.isEmptyList(mUnLoadImageList)) {
            return;
        }

        showLoadingDialog(R.string.text_uploading_dot);

        uploadFile();
    }

    //上传图片
    private void uploadFile() {
        final String path = mUnLoadImageList.get(0).getAbsolutePath();

        if (path == null) {
            return;
        }

        mFile = new File(path);

        if (mFile == null) {
            return;
        }

        CommonApiIO.getInstance().uploadImage(mFile, new ProgressRequestBody.ProgressListener() {
            @Override
            public void onProgress(long totalSize, long currSize, boolean done, int id) {

            }
        }, new APIRequestCallback<UploadImageJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(UploadImageJson res) {
                if (mImageList == null) {
                    dismissDialog();
                    return;
                }

                UploadImageJson.UploadImageData uploadImageData = res.getData();

                uploadImageData.setAbsolutePath(path);

                mImageList.add(uploadImageData);

                mUploadImageGridAdapter.notifyDataSetChanged();

                mUnLoadImageList.remove(0);

                if (mImageList.size() == UPLOAD_MAX_NUM || CommonUtils.isEmptyList(mUnLoadImageList)) {
                    dismissDialog();
                    return;
                }

                uploadFile();
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                dismissDialog();
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
            }
        });
    }

    //获取退款商品列表
    private void getRefundGoodsList() {
        if (StringUtils.isEmpty(mOrderNo)) {
            ToastUtils.showShort(getString(R.string.text_the_order_not_exist));
            return;
        }

        showLoadingDialog();

        OrderApiIO.getInstance().getRefundGoodsList(mOrderNo, mGoodsId, new APIRequestCallback<RefundGoodsJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(RefundGoodsJson res) {
                if (mRefundGoodsListAdapter == null) {
                    return;
                }

                setRefundMoney(res.getData().getTotal_price());

                mGoodsList.clear();
                mGoodsList.addAll(res.getData().getGoods_list());

                mReasonList.clear();
                if (res.getData().getReasons() != null) {
                    mReasonList.addAll(res.getData().getReasons());
                }

                mRefundGoodsListAdapter.notifyDataSetChanged();

                btn_refund_submit.setEnabled(true);
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    //设置退款金额
    private void setRefundMoney(String money) {
        if (StringUtils.isNumber(money)) {
            ll_refund_money.setEditText(money);
        }
    }
}
